package com.zero.manager_following.interceptor;

import cn.hutool.core.util.StrUtil;
import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTDecodeException;
import com.auth0.jwt.exceptions.JWTVerificationException;
import com.zero.manager_following.entity.User;
import com.zero.manager_following.exception.ServiceException;
import com.zero.manager_following.mapper.UserMapper;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

/**
 * 功能：限制非登录用户访问数据
 * 作者：zero
 * 日期：2024/9/8 12:13
 */

public class JWTInterceptor implements HandlerInterceptor {

    @Resource
    private UserMapper userMapper;

    @Override
    public boolean preHandle(HttpServletRequest req, HttpServletResponse resp, Object handler) {
        //header里面传过来的参数
        String token = req.getHeader("token");
        if (StrUtil.isBlank(token)) {
            // 从url参数里面获取 ?token=xxx
            token = req.getParameter("token");
        }
//        如果是注解标记的方法直接通过
        if (handler instanceof HandlerMethod) {
            AuthAccess authAccess = ((HandlerMethod) handler).getMethodAnnotation(AuthAccess.class);
            if (authAccess != null) {
                return true;
            }
        }
        //执行认证
        if (StrUtil.isBlank(token)) {
            throw new ServiceException("401", "请登录");
        }
        //获取token中的user.id
        String userId;
        try {
            userId = JWT.decode(token).getAudience().getFirst();
        } catch (JWTDecodeException e) {
            throw new ServiceException("401", "请登录");
        }

        User user = userMapper.selectById(Integer.parseInt(userId));
        if (user == null) {
            throw new ServiceException("401", "请登录");
        }

        //用户密码加密验证 token
        JWTVerifier jwtVerifier = JWT.require(Algorithm.HMAC256(user.getPassword())).build();
        try {
            jwtVerifier.verify(token);
        } catch (JWTVerificationException e) {
            throw new ServiceException("401", "请登录");
        }
        return true;
    }
}

